//
//  GamePlayLayer.cpp
//  MathSpeed
//
//  Created by ToanTM on 5/16/14.
//
//

#include "GamePlayLayer.h"
#include "GameConfig.h"
#include "GameMenuLayer.h"
#include "SimpleAudioEngine.h"
#include "NativeHelper.h"

CCScene* GamePlayLayer::scene(GameMode::GamePlayMode mode){
    CCScene* ret = CCScene::create();
    GamePlayLayer* layer = GamePlayLayer::createWithGameMode(mode);
    ret->addChild(layer);
    return ret;
}

GamePlayLayer* GamePlayLayer::createWithGameMode(GameMode::GamePlayMode mode){
    GamePlayLayer* ret = new GamePlayLayer();
    ret->setGameMode(mode);
    ret->init();
    ret->autorelease();
    return ret;
}

bool GamePlayLayer::init(){
    if (!CCLayer::init()) {
        return false;
    }
    this->setKeypadEnabled(true);
    
    CCSprite * mainBackground = CCSprite::create(IMAGE_BACKGROUND_MAIN);
    mainBackground->setAnchorPoint(ccp(0, 0));
    addChild(mainBackground);
    
    // init default value
    mScore = 0;
    mHighScore = CCUserDefault::sharedUserDefault()->getIntegerForKey(getStringOfGameMode()->getCString(), 0);
    mIsFirstTime = true;
    
    CCSize mWinSize = CCDirector::sharedDirector()->getWinSize();
    float paddingLabel = 39;
//    ccColor3B colorScore = ccc3(214, 196, 98);
    
    // Label
    
    mLbHighScore = CCLabelTTF::create(getStringForHightScore(), FONT_BERLIN_SANS_REGULAR, 45);
    mLbHighScore->setAnchorPoint(ccp(0, 1));
    //    mLbHighScore->setColor(colorScore);
    mLbHighScore->cocos2d::CCNode::setPosition(paddingLabel, mWinSize.height - 24);
    addChild(mLbHighScore);
    
    mLbScore = CCLabelTTF::create(getStringForScore(), FONT_BERLIN_SANS_REGULAR, 45);
    mLbScore->setAnchorPoint(ccp(0, 1));
//    mLbScore->setColor(colorScore);
    mLbScore->cocos2d::CCNode::setPosition(mLbHighScore->getPosition().x, mLbHighScore->getPosition().y - 59);
    addChild(mLbScore);
    
    CCString* strGameMode = this->getStringOfGameMode();
    CCLabelTTF* lbGameMode = CCLabelTTF::create(strGameMode->getCString(), FONT_BERLIN_SANS_BOLD, 60);
    lbGameMode->setAnchorPoint(ccp(0.5, 1));
//    lbGameMode->setColor(ccc3(216, 242, 113));
    lbGameMode->setPosition(ccp(mWinSize.width/2, mLbScore->getPosition().y - 114));
    addChild(lbGameMode);

    // Button
    mBtnCancel = CCMenuItemSprite::create(CCSprite::create(IMAGE_BUTTON_CANCEL_NORMAL), CCSprite::create(IMAGE_BUTTON_CANCEL_PRESS), this, menu_selector(GamePlayLayer::buttonCancelCallback));
    mBtnOk = CCMenuItemSprite::create(CCSprite::create(IMAGE_BUTTON_OK_NORMAL), CCSprite::create(IMAGE_BUTTON_OK_PRESS), this, menu_selector(GamePlayLayer::buttonOkCallback));
    CCMenu* menu = CCMenu::create(mBtnCancel, mBtnOk, NULL);
    menu->setPosition(ccp(mWinSize.width/2, mBtnOk->boundingBox().size.height));
    menu->alignItemsHorizontallyWithPadding(59);
    addChild(menu);
    
    float paddingPlay = 20;
    CCLabelTTF* lbEqual = CCLabelTTF::create("=", FONT_BERLIN_SANS_REGULAR, 60);
    lbEqual->setPosition(ccp(mWinSize.width/2, lbGameMode->getPosition().y - lbGameMode->boundingBox().size.height - 144));
    addChild(lbEqual);
    
    mLbPrLeft = CCLabelTTF::create("", FONT_BERLIN_SANS_BOLD, 60);
    mLbPrLeft->setAnchorPoint(ccp(1, 0.5));
    addChild(mLbPrLeft);
    
    mLbPrRight = CCLabelTTF::create("", FONT_BERLIN_SANS_BOLD, 60);
    mLbPrRight->setAnchorPoint(ccp(0, 0.5));
    addChild(mLbPrRight);
    
    mLbMatchOperator = CCLabelTTF::create("", FONT_BERLIN_SANS_BOLD, 60);
    mLbMatchOperator->setPosition(ccp(lbEqual->getPosition().x, lbEqual->getPosition().y + lbEqual->boundingBox().size.height / 2 + 40));
    addChild(mLbMatchOperator);
    
    mLbPrLeft->setPosition(ccp(mLbMatchOperator->getPosition().x - mLbMatchOperator->boundingBox().size.width - paddingPlay, mLbMatchOperator->getPosition().y));
    mLbPrRight->setPosition(ccp(mLbMatchOperator->getPosition().x + mLbMatchOperator->boundingBox().size.width + paddingPlay, mLbMatchOperator->getPosition().y));
    
    mLbResult = CCLabelTTF::create("", FONT_BERLIN_SANS_BOLD, 60);
    mLbResult->setPosition(ccp(lbEqual->getPosition().x, lbEqual->getPosition().y - lbEqual->boundingBox().size.height - paddingPlay));
    addChild(mLbResult);
    
    // init timer
    mSpBar = CCSprite::create(IMAGE_BAR_FILL);
    mSpBar->setAnchorPoint(ccp(0, 0.5));
    mSpBar->setPosition(ccp(15, lbGameMode->getPosition().y + 25));
    addChild(mSpBar);
    
    mGameOverLayer = NULL;
    // init matchObj
    mMatchObj = MathObj::create(this->mGameMode);
    mMatchObj->retain();

    CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(SOUND_START_GAME);
    
    // setCurrentScreen
    NativeHelper::getInstance()->setCurrentScreen(SCREEN_GAME_PLAY);
    updateScreenPlay();
    return true;
}

void GamePlayLayer::updateScreenPlay(){
    
    mLbScore->setString(getStringForScore());
    mLbPrLeft->setString(CCString::createWithFormat("%d",mMatchObj->paramLeft)->getCString());
    mLbPrRight->setString(CCString::createWithFormat("%d",mMatchObj->paramRight)->getCString());
    mLbResult->setString(CCString::createWithFormat("%d",mMatchObj->result)->getCString());
    mLbMatchOperator->setString(mMatchObj->getStringMatchOperator());
    
    // reset valur for timer
    mSpBar->setScale(1);
    if (mIsFirstTime) {
        mIsFirstTime = false;
    } else {
        CCAction *action = CCSequence::create(CCScaleTo::create(TIME_FOR_ONE_TIMES_PLAY, 0, 1), CCCallFunc::create(this, callfunc_selector(GamePlayLayer::timeOver)), NULL);
        mSpBar->stopAllActions();
        mSpBar->runAction(action);
    }
}

void GamePlayLayer::timeOver()
{
    this->gameOver();
}

void GamePlayLayer::buttonCancelCallback(cocos2d::CCObject *sender){
    CCLOG("buttonCancelCallback");
    CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(SOUND_TOUCH_EFFECTS);
    checkResult(false);
}

void GamePlayLayer::buttonOkCallback(cocos2d::CCObject *sender){
    CCLOG("buttonOkCallback");
    CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(SOUND_TOUCH_EFFECTS);
    checkResult(true);
}

void GamePlayLayer::checkResult(bool answer){
    if (mMatchObj->isRight == answer) {
        mScore++;
        mMatchObj->resetValue();
        this->updateScreenPlay();
    } else {
        gameOver();
    }
}

void GamePlayLayer::gameOver()
{
    CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(SOUND_FAIL);
    mSpBar->stopAllActions();
    if (mScore > mHighScore) {
        CCUserDefault::sharedUserDefault()->setIntegerForKey(getStringOfGameMode()->getCString(), mScore);
        mHighScore = mScore;
    }
    
    mBtnCancel->setEnabled(false);
    mBtnOk->setEnabled(false);
    
    if (mGameOverLayer == NULL) {
        mGameOverLayer = GameOverLayer::create(mScore, mHighScore, this, menu_selector(GamePlayLayer::buttonPlayCallback), menu_selector(GamePlayLayer::buttonMenuCallback));
        addChild(mGameOverLayer);
    } else {
        mGameOverLayer->setScore(mScore);
        mGameOverLayer->setHighScore(mHighScore);
        mGameOverLayer->refreshData();
    }
    showGameOverLayer();
}

CCString* GamePlayLayer::getStringOfGameMode()
{
    CCString *ret = NULL;
    switch (mGameMode) {
        case GameMode::HARD:
            ret = CCString::create("HARD");
            break;
        case GameMode::NORMAL:
            ret = CCString::create("NORMAL");
            break;
        default:
            ret = CCString::create("EASY");
            break;
    }
    return ret;
}

void GamePlayLayer::showGameOverLayer()
{
    mGameOverLayer->setPosition(-winSize.width, 0);
    mGameOverLayer->setVisible(true);
    mGameOverLayer->runAction(CCMoveTo::create(TIME_ANIMATION_APPEAR, ccp(0, 0)));
    
    // setCurrentScreen
    NativeHelper::getInstance()->setCurrentScreen(SCREEN_GAME_OVER);
}

void GamePlayLayer::gameOverLayerExitDone()
{
    switch (mNextActionOfGameOverLayer) {
        case REPLAY:
        {
            mGameOverLayer->setVisible(false);
            mBtnOk->setEnabled(true);
            mBtnCancel->setEnabled(true);
            mScore = 0;
            mMatchObj->resetValue();
            mLbHighScore->setString(getStringForHightScore());
            CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(SOUND_START_GAME);
            mIsFirstTime = true;
            // setCurrentScreen
            NativeHelper::getInstance()->setCurrentScreen(SCREEN_GAME_PLAY);
            updateScreenPlay();
            break;
        }
        case GO_TO_MENU:
        {
            CCScene* scene = GameMenuLayer::scene();
            CCDirector::sharedDirector()->replaceScene(scene);
        }
            break;
        default:
            break;
    }
}

void GamePlayLayer::hideGameOverLayer(){
    mGameOverLayer->setPosition(0, 0);
    CCAction *action = CCSequence::create(CCMoveTo::create(TIME_ANIMATION_APPEAR, ccp(winSize.width, 0)), CCCallFunc::create(this, callfunc_selector(GamePlayLayer::gameOverLayerExitDone)), NULL);
    mGameOverLayer->runAction(action);
}

void GamePlayLayer::buttonMenuCallback(CCObject* sender){
    CCLOG("buttonMenuCallback");
    CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(SOUND_TOUCH_EFFECTS);
    mNextActionOfGameOverLayer = GO_TO_MENU;
    hideGameOverLayer();
    
}

void GamePlayLayer::buttonPlayCallback(CCObject *sender){
    CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(SOUND_TOUCH_EFFECTS);
    CCLOG("buttonPlayCallback");
    mNextActionOfGameOverLayer = REPLAY;
    hideGameOverLayer();
    
}

void GamePlayLayer::setGameMode(GameMode::GamePlayMode mode){
    this->mGameMode = mode;
}

const char* GamePlayLayer::getStringForScore(){
    return CCString::createWithFormat("Score: %d", mScore)->getCString();
}

const char* GamePlayLayer::getStringForHightScore(){
    return CCString::createWithFormat("Best: %d", mHighScore)->getCString();
}

void GamePlayLayer::keyBackClicked(void)
{
    if (mGameOverLayer == NULL) {
        return;
    }
    if (!mGameOverLayer->isVisible()) {
        return;
    }
    buttonMenuCallback(NULL);
}
